package ink.xiaobaibai.utils;

import com.alibaba.fastjson.JSONObject;
import com.ejlchina.okhttps.HTTP;
import ink.xiaobaibai.common.WxCommon;
import org.apache.commons.lang3.StringUtils;

/**
 * @description: HTTP请求工具类
 * @author: 小白白
 * @create: 2021-05-19
 **/

public class WxLoginHttp {

    /**
     * 通过code获取用户信息的url
     */
    private static final String WEIXINLOGIN = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    private static HTTP http = OkHttp.http;

    public static String[] obtainOpenid(String code) {
        String url = String.format(WEIXINLOGIN, WxCommon.APPID, WxCommon.SECRET, code);
        String body = http.sync(url).get().getBody().toString();
        JSONObject jsonObject = JSONObject.parseObject(body);
        String openid = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");
        if (StringUtils.isBlank(openid) || StringUtils.isBlank(sessionKey)) {
            return null;
        }
        return new String[]{openid, sessionKey};
    }


}
